/* eslint-disable eqeqeq */
<template>
  <div class="file-tree-container">
    <el-input style="margin-bottom:10px"
              placeholder="搜索分类"
              prefix-icon="el-icon-search"
              v-model="filterText"></el-input>
    <div class="file-tree">
      <el-tree class="treeShow"
               :data="menuTree"
               :props="defaultProps"
               label="dir_name"
               node-key="p_project_dir_id"
               ref="organizationTree"
               :highlight-current="true"
               :filter-node-method="filterNode"
               :expand-on-click-node="true"
               @node-click="getId"
               @node-contextmenu="rihgtClick"
               :default-expanded-keys="selectedNodeList"
               :auto-expand-parent="false"
               draggable
               :accordion="false"
               :check-strictly="true"
               :show-checkbox="checkbox">
        <span class="slot-t-node"
              slot-scope="{ node, data }">
          <span v-show="!node.isEdit">
            <!-- 当节点类型为项目，且没有children时，不显示该节点，其它类型则显示 -->
            <!-- v-if="(data.children && data.children.length >= 1)||data.dir_type!=='project'" -->
            <span>
              <i class="fa"
                 :class="data.icon" />
              <span :class="[
                  data.p_project_dir_id >= maxexpandId
                    ? 'slot-t-node--label'
                    : ''
                ]"
                    :title="data.dir_name">{{ data.dir_name }}</span>
            </span>
            <!-- 当树形节点不存在子节点时，设置单独的图标 -->
            <!-- <span v-show="!data.children || data.children.length == 0">
              <i class="fa"
                 :class="data.icon"></i>
              <span :class="[
                  data.p_project_dir_id >= maxexpandId
                    ? 'slot-t-node--label'
                    : ''
                ]"
                    :title="data.dir_name">{{ data.dir_name }}</span>
            </span> -->
          </span>
          <!-- 编辑输入框 -->
          <span v-show="node.isEdit">
            <el-input class="slot-t-input"
                      size="mini"
                      autofocus
                      v-model="data.dir_name"
                      :ref="'slotTreeInput' + data.id"
                      @blur.stop="NodeBlur(node, data)"
                      @keyup.enter.native="NodeBlur(node, data)"></el-input>
          </span>
        </span>
      </el-tree>
    </div>

    <!--鼠标右键点击出现页面-->
    <div v-show="menuVisible">
      <el-menu id="rightClickMenu"
               class="el-menu-vertical"
               @select="handleRightSelect"
               active-text-color="#fff"
               text-color="#fff">
        <!-- 根据不同的状态，显示不同的右键自定义菜单（岗位与非岗位状态） -->
        <el-menu-item index="1"
                      class="menuItem">
          <i class="el-icon-plus" />
          <span slot="title">新增文件夹</span>
        </el-menu-item>

        <el-menu-item index="2"
                      v-if="DATA.dir_type === 'dir' && DATA.is_default === 2"
                      class="menuItem">
          <i class="el-icon-circle-plus-outline" />
          <span slot="title">修改</span>
        </el-menu-item>
        <el-menu-item index="3"
                      v-if="DATA.dir_type === 'dir' && DATA.is_default === 2"
                      class="menuItem">
          <i class="el-icon-menu" />
          <span slot="title">删除</span>
        </el-menu-item>
      </el-menu>
    </div>
    <!-- 新增或修改文件夹弹框 -->
    <el-dialog :modal="mode === 'edit'"
               width="600px"
               :title="(editNodeDialogStatus === 'create' ? '新增' : '修改') + '文件夹'"
               :visible.sync="editNodeDialogVisible">
      <el-form ref="editNodeForm"
               :model="editNodeDialogForm"
               :rules="editNodeFormRules"
               label-width="120px">
        <el-form-item label="文件夹名称"
                      prop="dir_name">
          <el-input v-model="editNodeDialogForm.dir_name"> </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="editNodeDialogVisible = false">取消</el-button>
        <el-button @click="editNode"
                   type="primary">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { userPermissionApi } from '@/services/UserPermission'
import { ProjectFileApi } from '@/services/ProjectCenter'
export default {
  name: 'leftTree',

  data () {
    return {
      judge: '',
      filterText: '',
      NODE: {},
      DATA: {},
      maxexpandId: 95, // 新增节点开始id
      non_maxexpandId: 95, // 新增节点开始id(不更改)
      isLoadingTree: true, // 是否加载节点树
      //   setTree:api.treelist,//节点树数据
      defaultProps: {
        children: 'children',
        label: 'dir_name',
        disabled: data => {
          return data.node_type !== '3'
        }
      },
      menuVisible: false,
      objectID: null,

      // 编辑或新增
      addOrEdit: 'add',
      // 选中的节点列表，用于刷新后展开到指定位置
      selectedNodeList: [],
      // 编辑节点弹框是否可见
      editNodeDialogVisible: false,
      // 编辑节点弹框数据对象
      editNodeDialogForm: {
        dir_name: '',
        dir_type: 'dir'
      },
      resetNodeDialogForm: {
        dir_name: '',
        dir_type: 'dir'
      },
      // 编辑节点弹框状态
      editNodeDialogStatus: 'create',
      // 编辑节点表单验证规则
      editNodeFormRules: {
        dir_name: [
          { required: true, message: '请输入文件夹名称', trigger: 'blur' }
        ]
      },
      requestParam: {
        node_no: '',
        node_type: ''
      }
    }
  },
  props: {
    curMenu: Object,
    assignedNode: Object,
    assignedTemplateNode: Object,
    // 复选框
    checkbox: {
      type: Boolean,
      default: false
    },
    // 是否启用右键菜单编辑功能
    rightMenu: {
      type: Boolean,
      default: true
    },
    callback: {
      type: Function
    },
    // 项目id，用于过滤
    projectId: {
      type: Number,
      default: 0
    },
    // 使用场景，编辑模式还是选择模式
    mode: {
      type: String,
      default: 'edit'
    }
  },
  components: {},
  methods: {
    // 新增
    onAdd () {
      this.judge = 1
    },
    onEdit () {
      this.judge = 2
    },
    // 节点点击事件获取id
    getId (data, node) {
      // console.log(data, 'click')
      let curData = JSON.parse(JSON.stringify(data))
      // console.log(curData.children_list)
      this.menuVisible = false
      this.$emit('update:curMenu', curData)

      if (
        (node.expanded || node.childNodes.length === 0) &&
        data.p_project_dir_id
      ) {
        this.addNodeList(data.p_project_dir_id)
      } else {
        this.removeNodeList(data.p_project_dir_id)
      }
    },
    // 当当前节点是展开操作时,将当前节点的object_id添加到selectedNodeList中，为了刷新数据后能够展开到指定位置
    addNodeList (id) {
      let index = this.selectedNodeList.indexOf(id)
      if (index < 0) {
        this.selectedNodeList.push(id)
      }
    },
    // 当前节点是收起操作时，将当前节点的object_id从selectedNodeList中移除
    removeNodeList (id) {
      let index = this.selectedNodeList.indexOf(id)
      if (index >= 0) {
        this.selectedNodeList.splice(index, 1)
      }
    },
    // 对树节点进行筛选时执行的方法，返回 true 表示这个节点可以显示，返回 false 则表示这个节点会被隐藏
    filterNode (value, data) {
      console.log('value:', value)
      console.log('data:', data)
      if (!value) return true
      return data.dir_name.indexOf(value) !== -1
    },
    // 右键点击事件
    rihgtClick (event, object, value, element) {
      this.DATA = object
      this.NODE = value

      if (this.rightMenu && this.DATA.dir_type !== 'company') {
        this.menuVisible = !this.menuVisible
        console.log(object, value, event, 'right')
        document.addEventListener('click', e => {
          this.menuVisible = false
        })
        let menu = document.querySelector('#rightClickMenu')
        /* 菜单定位基于鼠标点击位置 */
        menu.style.left = event.clientX + 40 + 'px'
        menu.style.top = event.clientY + 'px'
        menu.style.position = 'fixed' // 为新创建的DIV指定绝对定位
        menu.style.width = 160 + 'px'
      }
    },
    // 右键弹出的菜单点击事件
    handleRightSelect (key) {
      if (key === '1') {
        // 新增文件夹
        this.editNodeDialog('create', {})
      } else if (key === '2') {
        // 修改文件夹
        this.editNodeDialog('update', this.DATA)
      } else if (key === '3') {
        // 删除
        this.$confirm('此操作将永久删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.deleteNode(this.DATA.p_project_dir_id)
          })
          .catch(() => { })
      }
      this.menuVisible = false
    },
    // 显示编辑文件夹弹框
    editNodeDialog (type, data) {
      this.editNodeDialogForm.dir_name = ''
      this.editNodeDialogStatus = type
      this.editNodeDialogForm = Object.assign(this.editNodeDialogForm, data)
      this.editNodeDialogVisible = true
    },
    // 编辑文件夹弹框确认事件
    editNode () {
      this.$refs.editNodeForm.validate(valid => {
        if (valid) {
          if (this.editNodeDialogStatus === 'create') {
            this.createNode()
          } else {
            this.updateNode()
          }
        }
      })
    },
    // 新增文件夹
    createNode () {
      this.editNodeDialogForm.project_id = this.DATA.project_id
      this.editNodeDialogForm.pid = this.DATA.p_project_dir_id
      ProjectFileApi.createFileTreeNode({
        data: this.editNodeDialogForm
      }).then(res => {
        if (res.code === 0) {
          this.$message.success('新建文件夹成功')
          this.$emit('callback', '')
          this.editNodeDialogVisible = false
        }
      })
    },
    // 修改文件夹
    updateNode () {
      this.editNodeDialogForm.id = this.DATA.p_project_dir_id
      ProjectFileApi.updateFileTreeNode({
        data: this.editNodeDialogForm
      }).then(res => {
        if (res.code === 0) {
          this.$message.success('修改文件夹成功')
          this.$emit('callback', '')
          this.editNodeDialogVisible = false
        }
      })
    },
    // 删除文件夹
    deleteNode (id) {
      ProjectFileApi.deleteFileTreeNode({
        data: {
          id: id
        }
      }).then(res => {
        if (res.code === 0) {
          this.$message.success('删除文件夹成功')
          this.$emit('callback', '')
          this.editNodeDialogVisible = false
        }
      })
    },
    // 编辑文件夹弹框关闭事件
    dialogClose () {
      let resetForm = JSON.parse(JSON.stringify(this.resetNodeDialogForm))
      this.editNodeDialogForm = Object.assign(
        this.editNodeDialogForm,
        resetForm
      )
      this.$refs.editNodeForm.resetFields()
    },
    NodeBlur (n, d) {
      // 输入框失焦
      if (n.isEdit) {
        this.$set(n, 'isEdit', false)
      }
      this.$nextTick(() => {
        this.$refs['slotTreeInput' + d.id].$refs.input.focus()
      })
    },
    NodeDel (n, d) {
      // 删除节点
      console.log(d, 'delete tree')
      if (d.children && d.children.length !== 0) {
        this.$message.error('此菜单有子菜单，不可删除！')
        return false
      } else {
        // 二次确认
        let ConfirmFun = () => {
          this.$confirm('是否删除此菜单？', '提示', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning'
          })
            .then(() => {
              if (this.DATA.node_type === '1') {
                this.deleteOrg()
              } else if (this.DATA.node_type === '2') {
                this.deleteDept()
              } else if (this.DATA.node_type === '3') {
                this.deleteJob()
              }
            })
            .catch(() => { })
        }
        // 判断是否是新增节点
        ConfirmFun()
      }
    },

    // 处理传入的数据，因为后端都是children_list，需要手动赋值一个children字段
    handelData (arr, path) {
      if (Object.prototype.toString.call(arr) === '[object Array]') {
        for (let i = 0; i < arr.length; i++) {
          let item = arr[i]
          // 显示指定项目，过滤其它项目
          if (
            this.projectId !== 0 &&
            item.dir_type === 'project' &&
            item.project_id !== this.projectId
          ) {
            // arr.splice(i, 1)
            // i--
          } else {
            if (item.dir_type === 'company') {
              item.icon = 'fa-building'
            } else if (item.dir_type === 'project') {
              item.icon = 'fa-institution'
            } else if (item.dir_type === 'dir' && item.is_default === 1) {
              item.icon = 'fa-lock'
            } else {
              item.icon = 'fa-folder'
            }
            // 当前节点到顶级的路径
            item.path = path + item.p_project_dir_id + '/'
            if (item.children) {
              this.handelData(
                item.children,
                path + item.p_project_dir_id + '/'
              )
            }

            if (item.sid) {
              item.menu_id = item.sid
            }
            if (item.menu_id === '') {
              item.menu_id = '0'
            }
          }
        }
        // arr.map((item) => {

        // })
        return arr
      }
    },
    // 获取组织树
    getOrganizationTree () {
      userPermissionApi
        .getOrganizationTree({
          data: this.requestParam
        })
        .then(res => {
          if (res.code === 0) {
            this.$store.dispatch('setOrgainzationTree', res.data)
            window.localStorage.setItem(
              'platformOrganizationTree',
              JSON.stringify(res.data)
            )
          }
        })
    },
    // 编辑成功回调
    editCallback () {
      this.getOrganizationTree()
    }
  },
  watch: {
    filterText (val) {
      this.$refs.organizationTree.filter(val)
    }
  },
  computed: {
    menuTree () {
      let store = this.$store.state.projectFileTree
      let storage =
        JSON.parse(window.localStorage.getItem('projectFileTree')) || []
      let treeData = store.length > 0 ? store : storage
      treeData = JSON.parse(JSON.stringify(treeData))
      if (Object.prototype.toString.call(treeData) === '[object Array]') {
        treeData = this.handelData(treeData, '')
      } else {
        treeData = this.handelData([treeData], '')
      }

      return treeData
    }
  },
  created () {
    // this.treelist=this.messageinfo
    this.selectedNodeList = []
  },
  mounted () { }
}
</script>
<style lang="scss" scoped>
/* 去掉默认的树形图标 */
/* .treeShow /deep/ .el-tree-node__content>.el-tree-node__expand-icon {
  display: none;
} */
#save-style {
  background: rgba(26, 188, 156, 1);
  color: white;
}
#back-style {
  background: rgba(26, 188, 156, 1);
}
#show-ellipsis {
  //display: block;
  width: 100%;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.popover-new {
  /* position: absolute!important;
    right: 0;
    bottom: 0; */
}
/*顶部按钮*/
.slot-tree .slot-t-top {
  margin-bottom: 15px;
}
.slot-tree .slot-t-node span {
  display: inline-block;
}
/*节点*/
.slot-tree .slot-t-node--label {
  font-weight: 600;
}
/*输入框*/
.slot-tree .slot-t-input .el-input__inner {
  height: 26px;
  line-height: 26px;
}
/*按钮列表*/
.slot-tree .slot-t-node .slot-t-icons {
  display: none;
  margin-left: 10px;
}
.slot-tree .slot-t-icons .el-button + .el-button {
  margin-left: 6px;
}
.slot-tree .el-tree-node__content:hover .slot-t-icons {
  display: inline-block;
}

/*************************标签鼠标右击页面样式******************************/
.el-menu-vertical {
  /* border: 3px solid rgb(84, 92, 100); */
  border: 2px solid #f5f7fa;
  border-radius: 10px;
  z-index: 100;
}
.el-menu-vertical i {
  color: #777777;
}
.menuItem {
  height: 40px;
  line-height: 40px;
  /* background-color: #545c64; */
  background-color: #f5f7fa;
  font-size: 14px;
}
/deep/ .menuItem i {
  color: #606266 !important;
}
/deep/ .menuItem span {
  color: #606266 !important;
}
.menuItem:hover {
  background-color: #409eff;
}
/deep/ .menuItem:hover i {
  color: #fff !important;
}

/deep/ .menuItem:hover span {
  color: #fff !important;
}
.add_tips /deep/ .el-form-item__label {
  /* padding-left: 28px; */
}
.file-tree-container {
  margin-top: 20px;
  width: 350px;
  // min-height: 500px;
  height: 500px;
  background-color: #fff;
  position: relative;
  overflow-y: scroll;
  .file-tree {
    width: 100%;
    height: auto;
    overflow-y: scroll;
  }
}
</style>
